/**
 * Global functions and variables are bad practice and EVIL!
 * Base Cart object literal so everything is nice and namespaced
 */
var Cart = {
	/**
	 * Tax rate
	 * @var decimal
	 */
	taxRate: 0.0971,

	/**
	 * Cart items added. Obviously adding here would be bad since leaving page wipes out cart.
	 * If client side cart saving was a requirement, then we should use local storage or sessino storage
	 * @var array
	 */
	cartItems: [],

	/**
	 * API endpoints, assuming there are multiple
	 * @var object
	 */
	endpoint: {
		addItem: '/api.php',
		delItem: '/api.php'
	},

	/**
	 * Listen for form submit, hijack and make api call to add item/get price
	 */
	initAddItem: function () {
		$('form[name="cart-form"]').on('submit', function (e) {
			e.preventDefault();

			// Get item name value
			var itemName = $('input[name="itemName"]').val();

			// Get item quantity value
			var itemQuantity = $('input[name="itemQuantity"]').val();

			// Restrict quantity to > 1 && < 100
			if (itemQuantity <= 0 || itemQuantity > 100) {
				return Cart.alert('You must enter a valid quantity (1-100)');
			}

			// Hide any (possibly) previous errors
			$('#alert-box').hide();

			$.ajax({
				url: Cart.endpoint.addItem,
				type: 'POST',
				dataType: 'json',
				data: encodeURI('itemName=' + itemName + '&itemQuantity=' + itemQuantity),

				success: function (data) {
					var item = {
						itemName: itemName,
						itemQuantity: parseInt(itemQuantity, 10),
						itemPrice: parseFloat(data.data.price),
						itemTotal: parseFloat(data.data.total)
					};

					// Push new object containing line iten name, quantity and price into cartItems array
					Cart.cartItems.push(item);

					// Call update cart method to recalc cart contents, tax, totals and re-populate cart div
					Cart.update();
				},

				error: function () {
					Cart.alert('There was a problem retrieving response from API.');
				}
			});
		});
	},

	/**
	 * Update the cart output by looping through each cart item. Display name, quantity, totals, tax
	 */
	update: function () {
		var subTotal = parseFloat('0.00'),
			total = parseFloat('0.00'),
			tax = parseFloat('0.00'),
			i = 0,
			c = 0,
			item = null,
			html = null;

		// Clear cart item list
		$('#cart-items').children().remove();

		// Loop through each cart item and add to balance
		for (i = 0, c = Cart.cartItems.length; i < c; i++) {
			// Get reference to cart item
			item = Cart.cartItems[i];

 			// Add item total to balance
 			subTotal = (parseFloat(subTotal) + parseFloat(item.itemTotal)).toFixed(2);

 			// Append the item to the cart item list
 			html = "<li>\n" +
 				 ' <strong>' + item.itemName + '</strong><br/>' + "\n" +
 				 '(' + item.itemQuantity + ') x $' + item.itemPrice + ' = $' + item.itemTotal.toFixed(2) + '</li>';
 			$('#cart-items').append(html);
		}

		// Calculate tax
		tax = (parseFloat(subTotal) * parseFloat(Cart.taxRate)).toFixed(2);

		// Calculate total
		total = (parseFloat(subTotal) + parseFloat(tax)).toFixed(2);

		// Add divider and subtotal
		$('#cart-items').append("<li><hr/></li>\n<li>Sub-Total: " + subTotal + "</li>\n");

		// Add tax
		$('#cart-items').append("<li>Tax: $" + tax + "</li>\n");

		// Add total
		$('#cart-items').append("<li>Total: $" + total + "</li>\n");
	},

	/**
	 * Set alert box message, show alert box
	 * @param string message
	 * @return bool
	 */
	alert: function (message) {
		$('#alert-box').html(message);
		$('#alert-box').show();
		return true;
	},

	/**
	 * Similiar concept as server-side controller for MVC, but very primitive.
	 * Could perform uri checks here (routing)
	 */
	Controller: {
		/**
		 * Add global/site wide hooks/event listeners here
		 */
		init: function () {
			// Load global hooks
			Cart.initAddItem();
		}
	}
};

/**
 * Document Ready
 */
$(function () {
	Cart.Controller.init();
});
